<template>
    <div class="view-cart">
      <h2>查看购物车</h2>
      <el-divider></el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card v-if="cart.length > 0" class="cart-container">
            <div slot="header" class="clearfix">
              <div class="title">购物车详情</div>
              <el-button type="text" @click="clearCart">清空购物车</el-button>
            </div>
            <el-row class="cart-items" v-for="item in cart" :key="item.id">
              <el-col :span="6">
                <el-image :src="item.imageUrl" fit="cover"></el-image>
              </el-col>
              <el-col :span="12">
                <div class="item-details">
                  <span class="item-name">{{ item.name }}</span>
                  <span class="item-price">{{ '¥' + item.price }}</span>
                </div>
              </el-col>
              <el-col :span="6" class="item-actions">
                <el-input-number v-model="item.quantity" controls-position="right" :min="1" @change="updateCart"></el-input-number>
                <el-button type="danger" @click="removeFromCart(item.id)">移除</el-button>
              </el-col>
            </el-row>
          </el-card>
          <p v-else>购物车为空</p>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { ElDivider, ElRow, ElCol, ElCard, ElImage, ElButton, ElInputNumber } from 'element-plus';
  
  const cart = ref(JSON.parse(localStorage.getItem('cart')) || []);
  
  const updateCart = () => {
    localStorage.setItem('cart', JSON.stringify(cart.value));
  };
  
  const removeFromCart = (productId) => {
    const index = cart.value.findIndex(item => item.id === productId);
    if (index !== -1) {
      cart.value.splice(index, 1);
      localStorage.setItem('cart', JSON.stringify(cart.value));
    }
  };
  
  const clearCart = () => {
    cart.value = [];
    localStorage.removeItem('cart');
  };
  </script>
  
  <style scoped>
  .view-cart {
    padding: 20px;
  }
  .cart-container {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
  .title {
    font-size: 18px;
    font-weight: bold;
  }
  .cart-items {
    margin-top: 20px;
  }
  .item-details {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .item-name {
    font-size: 16px;
  }
  .item-price {
    font-size: 16px;
    color: #f56c6c;
  }
  .item-actions {
    display: flex;
    align-items: center;
  }
  </style>
  